<template>
  <div>加密数据{{ showEncodeTxt }}</div>
  <span @click="handleEncode">点击加密</span>
  <div>解密数据{{showDecodeTxt}}</div>
  <span @click="handleDecode">点击解密</span>
</template>

<script setup>
import {ref} from 'vue'
const txt = '我是待加密数据'
const showEncodeTxt = ref(null)
const showDecodeTxt = ref(null)
let pub = null
//
const getMessageEncoding = () => {
  let enc = new TextEncoder();
  return enc.encode(txt);
}
window.crypto.subtle.generateKey(
  {
    name: "RSA-OAEP",
    modulusLength: 2048,
    publicExponent: new Uint8Array([1, 0, 1]),
    hash: "SHA-256",
  },
  true,
  ["encrypt", "decrypt"]
).then((keyPair) => {
  pub = keyPair
});
const handleEncode = async () => {
  let encoded = getMessageEncoding();
  showEncodeTxt.value = await window.crypto.subtle.encrypt(
    {
      name: "RSA-OAEP"
    },
    pub.publicKey,
    encoded
  );
}
const handleDecode = async () => {
  let decrypted = await window.crypto.subtle.decrypt(
    {
      name: "RSA-OAEP"
    },
    pub.privateKey,
    showEncodeTxt.value
  );

  let dec = new TextDecoder();
  showDecodeTxt.value = dec.decode(decrypted);
}
</script>

<style scoped lang="scss">

</style>